#!/bin/sh
# This regression test is a part of SIPp.
# A write refused on a TCP connection being made again (-max_reconnect)
# resets it as a failed read does. It only warned, and the next read
# took the connection for one the peer closed: over -t t1 the INVITE
# waited for ever, and a 3PCC controller A stopped reconnecting.
. "`dirname "$0"`/../functions"; init

# The UAS listens only after the UAC's first attempts were refused; the
# INVITE they left waiting goes once one is not.
(sleep 1; sipp -nostdin -sn uas -t t1 -i 127.0.0.1 -p 27871 -m 1 \
    >/dev/null 2>&1) &
uas=$!
sippfg -sn uac -t t1 -i 127.0.0.1 -p 27870 127.0.0.1:27871 -m 1 \
    -max_reconnect 10 -reconnect_sleep 300 -reconnect_close false \
    -timeout 5 -timeout_error >/dev/null 2>&1
uac=$?
kill $uas 2>/dev/null
wait $uas 2>/dev/null

# B answers A's first command, resets the connection, and listens again
# a second later, while A's commands keep coming: it answers those on
# A's next connection.
rm -f answered.log
perl -e '
    use IO::Socket::INET; use Socket;
    alarm 10;
    sub listener { IO::Socket::INET->new(LocalAddr => "127.0.0.1:27872", Listen => 1, ReuseAddr => 1) or die }
    sub answer {
        my ($c, $log) = @_;
        my ($cmd, $d) = ("", "");
        while (defined $c->recv($d, 4096) && $d ne "") {
            $cmd .= $d;
            while ($cmd =~ s/^([^\e]*)\e//) {
                my ($id) = $1 =~ /Call-ID: *(\S+)/i;
                print $c "Call-ID: $id\r\n\e";
                return unless $log;
                open(my $f, ">>", $log); print $f "$id\n"; close($f);
            }
        }
    }
    my $l = listener();
    my $c = $l->accept() or die;
    answer($c);
    select(undef, undef, undef, 0.2);
    setsockopt($c, SOL_SOCKET, SO_LINGER, pack("ii", 1, 0));
    close($c); close($l);
    sleep 1;
    $l = listener();
    $c = $l->accept() or die;
    answer($c, "answered.log");' &
peer=$!
sleep 1
sippfg -sf a.xml -3pcc 127.0.0.1:27872 -i 127.0.0.1 -p 27873 -m 5 -r 2 \
    -max_reconnect -1 -reconnect_sleep 100 -reconnect_close false \
    -timeout 5 >/dev/null 2>&1
kill $peer 2>/dev/null
wait $peer 2>/dev/null
answered=`cat answered.log 2>/dev/null | wc -l`
rm -f answered.log

if test $uac -ne 0; then
    fail "-t t1: the UAC ended with $uac"
elif test $answered -eq 0; then
    fail "-3pcc: A did not connect again"
else
    ok
fi
